﻿Imports Runa.Foundation.CompoentModel
Imports Microsoft.Xna.Framework.Input
Imports Microsoft.Xna.Framework
Imports Runa.Foundation.Messaging

Namespace Global.Runa.UI.Input

    Public Class KeyboardInputHandler
        Inherits InputHandler

        Private m_state As New KeyboardState
        Private m_IsAnyKeyPressed As Boolean = False
        Private m_PressedKeys() As Keys = New Keys() {}

        Public Property IsAnyKeyPressed() As Boolean
            Get
                Return Me.m_IsAnyKeyPressed
            End Get
            Set(value As Boolean)
                Me.m_IsAnyKeyPressed = value
            End Set
        End Property

        <MessageMapping(New String() {"KeyUp", "KeyDown"}, New MessageType() {MessageType.WM_KEYUP, MessageType.WM_KEYDOWN})> _
        Public Property PressedKeys() As Keys()
            Get
                Return Me.m_PressedKeys
            End Get
            Set(value As Keys())
                Dim upKeys = (From item In Me.m_PressedKeys Where Not value.Contains(item) Select item).ToArray()
                If upKeys.Length > 0 Then
                    RaiseEvent KeyUp(Me, New KeyboradInputEventArgs(MessageType.WM_KEYUP, Me.m_state))
                    MyBase.OnDataArrived(Me, New KeyboradInputEventArgs(MessageType.WM_KEYUP, Me.m_state,
                        New ChangedPropertyInf(Of Keys())("UpKeys", upKeys).ConvertToBase()))
                End If
                Dim downKeys = (From item In value Where Not Me.m_PressedKeys.Contains(item) Select item).ToArray()
                If downKeys.Length > 0 Then
                    RaiseEvent KeyDown(Me, New KeyboradInputEventArgs(MessageType.WM_KEYDOWN, Me.m_state))
                    MyBase.OnDataArrived(Me, New KeyboradInputEventArgs(MessageType.WM_KEYDOWN, Me.m_state,
                        New ChangedPropertyInf(Of Keys())("DownKeys", downKeys).ConvertToBase()))
                End If
                Me.m_PressedKeys = value
            End Set
        End Property

        Public Event KeyUp(ByVal sender As Object, ByVal e As KeyboradInputEventArgs)
        Public Event KeyDown(ByVal sender As Object, ByVal e As KeyboradInputEventArgs)

        Public Sub New(ByVal g As Game)
            MyBase.New(g)
        End Sub

        Public Overrides Sub Update(gameTime As Microsoft.Xna.Framework.GameTime)
            If Me.Game.IsActive And Me.Enabled Then
                Me.m_state = Microsoft.Xna.Framework.Input.Keyboard.GetState()
                Me.PressedKeys = Me.m_state.GetPressedKeys()
                If Me.PressedKeys.Length > 0 Then
                    Me.IsAnyKeyPressed = True
                Else
                    Me.IsAnyKeyPressed = False
                End If
            End If
        End Sub

    End Class

End Namespace
